package com.jp.knowledge.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.AttentionGroupSelectAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AttentionData;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.attention.AttentionGroupDetailModel;
import com.jp.knowledge.model.attention.AttentionSelectGroupModel;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/3/28.
 */

public class AttentionSelectGroupDialog extends Dialog implements ResultSubscriber.OnResultListener {

    private static final int GET_GROUP_DATA_CODE = 0x01;
    private static final int ATTENTION_GROUP_CREATE = 0x02;
    private static final int ATTENTION_TO_LIST_CODE = 0x03;
    private static final int ATTENTION_TO_GROUP_CODE = 0x04;

    private Context context;
    private List<AttentionGroupDetailModel> groupDetailModelsCache;
    private List<AttentionSelectGroupModel.ListBean> listBeen;
    private AttentionGroupSelectAdapter adapter;
    private HeadLineData headLineData;

    private View contentView;
    private TextView createNewGroupBtn;
    private RecyclerView groupListRv;

    private LoadingDialog loadingDialog;
    private CommDialog createGroupDialog;

    private String cachePath;
    private FileCacheManager fileCacheManager;

    public AttentionSelectGroupDialog(Context context) {
        super(context, R.style.custom_idalgo);
        this.setCanceledOnTouchOutside(true);
        this.context = context;
        this.listBeen = new ArrayList<>();

        this.contentView = View.inflate(context, R.layout.dialog_attention_select_group, null);
        this.createNewGroupBtn = (TextView) contentView.findViewById(R.id.create_new_group);
        this.groupListRv = (RecyclerView) contentView.findViewById(R.id.group_list_rv);
        this.contentView.setTag(-1);

        groupListRv.setHasFixedSize(true);
        groupListRv.setLayoutManager(new LinearLayoutManager(context));
        adapter = new AttentionGroupSelectAdapter(context, listBeen);
        groupListRv.setAdapter(adapter);
        adapter.setOnAttentionBtnClickListener(new AttentionGroupSelectAdapter.OnAttentionBtnClickListener() {
            @Override
            public void onAtteneionBtnClick(int position) {
                doAttention(position);
            }
        });
        setData(null, 0);
        createNewGroupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createGroupDialog.setContent("");
                createGroupDialog.show();
            }
        });
        setContentView(contentView);
        getWindow().getAttributes().width = (int)(DensityUtil.getScreenWidth() * 0.8);
        getWindow().getAttributes().height = (int)(DensityUtil.getScreenHeight() * 0.6);

        loadingDialog = new LoadingDialog(context);
        createGroupDialog = new CommDialog(context);
        createGroupDialog.setEditHint("新建分组");
        createGroupDialog.setRightClickDismiss(false);
        createGroupDialog.setShowWithKeyword(true);
        createGroupDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String groupName = createGroupDialog.getEditText();
                if(groupName.trim().length() == 0){
                    ToasUtil.toast(AttentionSelectGroupDialog.this.context, "请输入有效的组名");
                } else{
                    for(AttentionSelectGroupModel.ListBean model : listBeen)
                        if(groupName.equals(model.getTitle())){
                            ToasUtil.toast(AttentionSelectGroupDialog.this.context, "抱歉，\"" + groupName + "\"已存在");
                            return;
                        }
                    createGroupDialog.setTag(groupName);
                    groupCreate(groupName);
                    createGroupDialog.dismiss();
                }
            }
        });
    }

    public void show(HeadLineData data, int position) {
        contentView.setTag(position);
        groupListRv.scrollToPosition(0);
        headLineData = data;
        if(getAttentionGroupCacheData(headLineData))
            getAttentionGroupData(headLineData);
        super.show();
    }

    private void setData(List<AttentionSelectGroupModel.ListBean> listBeen, int isSubscribe){
        this.listBeen.clear();
        AttentionSelectGroupModel.ListBean data = new AttentionSelectGroupModel.ListBean();
        data.setTitle("监控列表");
        data.setId("attentionList");
        data.setIsJoin(isSubscribe);
        this.listBeen.add(data);
        if(listBeen != null && listBeen.size() > 0)
            this.listBeen.addAll(listBeen);
        adapter.updateAdapter(this.listBeen);
    }

    /* 获取监控组数据 */
    private void getAttentionGroupData(HeadLineData data){
        JsonObject param = new JsonObject();
        param.addProperty("id", data.getId());
        param.addProperty("type", data.getType());
        HttpHelper.getInstance(context).attentionGroupData(param, GET_GROUP_DATA_CODE, AttentionSelectGroupDialog.this);
    }

    /* 创建组 */
    private void groupCreate(String title){
        JsonObject param = new JsonObject();
        param.addProperty("title", title);
        HttpHelper.getInstance(context).attentionGroupCreate(param, ATTENTION_GROUP_CREATE, this);
    }

    /* 监控 */
    private void doAttention(int position){
        AttentionSelectGroupModel.ListBean data = listBeen.get(position);
        data.setIsJoin(data.getIsJoin()==1 ? 0 : 1);
        adapter.notifyDataSetChanged();
        if("attentionList".equals(data.getId())){
            JsonObject param = new JsonObject();
            param.addProperty("id", headLineData.getId());
            param.addProperty("type", headLineData.getType());
            HttpHelper.getInstance(context).subscribeOperate(param, position*10+ATTENTION_TO_LIST_CODE, this);
        } else{
            JsonObject param = new JsonObject();
            param.addProperty("id", headLineData.getId());
            param.addProperty("type", headLineData.getType());
            param.addProperty("subjectId", listBeen.get(position).getId());
            param.addProperty("op", listBeen.get(position).getIsJoin());
            HttpHelper.getInstance(context).attentionGroupConditionAdd(param, position*10+ATTENTION_TO_GROUP_CODE, this);
        }
    }

    /* 获取监控组缓存数据 */
    private boolean getAttentionGroupCacheData(final HeadLineData data){
        if(fileCacheManager != null)
            return true;
        fileCacheManager = new FileCacheManager();
        cachePath = context.getCacheDir().getPath() + "/attentionGroup_myGroup_0.dat";
        Observable.create(new Observable.OnSubscribe<List<AttentionGroupDetailModel>>() {
            @Override
            public void call(Subscriber<? super List<AttentionGroupDetailModel>> subscriber) {
                List<AttentionGroupDetailModel> data = (List<AttentionGroupDetailModel>)fileCacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AttentionGroupDetailModel>>() {
                    @Override
                    public void onCompleted() {
                        getAttentionGroupData(data);
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<AttentionGroupDetailModel> list) {
                        if(list != null && list.size() > 0) {
                            groupDetailModelsCache = new ArrayList<>();
                            List<AttentionSelectGroupModel.ListBean> data = new ArrayList<>();
                            for (AttentionGroupDetailModel cacheModel : list) {
                                AttentionSelectGroupModel.ListBean bean = new AttentionSelectGroupModel.ListBean();
                                bean.setId(cacheModel.getId());
                                bean.setTitle(cacheModel.getTitle());
                                bean.setIsJoin(0);
                            }
                            setData(data, 0);
                        }
                        onCompleted();
                    }
                });
        return false;
    }

    private void saveCache(final Object object, final String path){
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    fileCacheManager.wirteObject(object, path);
                }
            }).start();
        }catch (Exception e){}
    }

    @Override
    public void onStart(int requestType) {
        if (requestType == ATTENTION_GROUP_CREATE){
            loadingDialog.show();
        }else if(requestType == GET_GROUP_DATA_CODE){
            for(AttentionSelectGroupModel.ListBean listBean : listBeen)
                listBean.setIsJoin(-1);
            adapter.updateAdapter(listBeen);
        }
    }
    @Override
    public void onCompleted(int requestType) {
        if(requestType == ATTENTION_GROUP_CREATE) {
            loadingDialog.cancel();
        }else if(requestType % 10 == ATTENTION_TO_LIST_CODE || requestType % 10 == ATTENTION_TO_GROUP_CODE){
            if(listener == null)
                return;
            for(AttentionSelectGroupModel.ListBean listBean : listBeen){
                if(listBean.getIsJoin() == 1){
                    listener.onAttentionStatusChanged((int) contentView.getTag(), true);
                    return;
                }
            }
            listener.onAttentionStatusChanged((int) contentView.getTag(), false);
        }
    }
    @Override
    public void onError(int requestType) {
        if(requestType % 10 == ATTENTION_TO_LIST_CODE || requestType % 10 == ATTENTION_TO_GROUP_CODE){
            int position = requestType/10;
            listBeen.get(position).setIsJoin(listBeen.get(position).getIsJoin()==1 ? 0 : 1);
            adapter.notifyItemChanged(position);
        } else if(requestType == GET_GROUP_DATA_CODE){
            for(AttentionSelectGroupModel.ListBean listBean : listBeen)
                listBean.setIsJoin(-2);
            adapter.updateAdapter(listBeen);
        }
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else if(requestType == GET_GROUP_DATA_CODE) {
            AttentionSelectGroupModel attentionSelectGroupModel = data.getEntity(AttentionSelectGroupModel.class);
            listBeen.clear();
            if (attentionSelectGroupModel == null)
                return;
            List<AttentionSelectGroupModel.ListBean> groupList = attentionSelectGroupModel.getList();
            setData(groupList, attentionSelectGroupModel.getIsSubscribe());
            if (groupDetailModelsCache == null)
                groupDetailModelsCache = new ArrayList<>();
            if(groupDetailModelsCache.size() > 0 || groupList == null || groupList.size() == 0)
                return;
            for (AttentionSelectGroupModel.ListBean bean : groupList) {
                AttentionGroupDetailModel model = new AttentionGroupDetailModel();
                model.setId(bean.getId());
                model.setTitle(bean.getTitle());
                groupDetailModelsCache.add(model);
            }
            saveCache(groupDetailModelsCache, cachePath);
        } else if(requestType == ATTENTION_GROUP_CREATE){
            AttentionGroupDetailModel model = new AttentionGroupDetailModel();

            AttentionSelectGroupModel.ListBean bean = new AttentionSelectGroupModel.ListBean();
            bean.setIsJoin(0);
            bean.setId(data.getData().toString());
            bean.setTitle((String) createGroupDialog.getTag());
            listBeen.add(bean);
            adapter.updateAdapter(listBeen);

            model.setId(bean.getId());
            model.setTitle(bean.getTitle());
            model.setConditionNum(0);
            model.setCountNum(0);
            model.setNewNum(0);
            if(groupDetailModelsCache == null)
                groupDetailModelsCache = new ArrayList<>();
            groupDetailModelsCache.add(model);
            saveCache(groupDetailModelsCache, cachePath);
        } else if(requestType % 10 == ATTENTION_TO_LIST_CODE || requestType % 10 == ATTENTION_TO_GROUP_CODE){
            /* 发送广播刷新雷达 */
            AttentionData attentionData = new AttentionData();
            attentionData.setId(headLineData.getId());
            attentionData.setIcon(headLineData.getIcon());
            attentionData.setType(headLineData.getType());
            attentionData.setTitle(headLineData.getTitle());
            attentionData.setSource(headLineData.getSource());
            attentionData.setNewNum(0);
            attentionData.setCountNum(0);
            attentionData.setAddress(headLineData.getAddress());
            attentionData.setAttentionTime(System.currentTimeMillis());
            attentionData.setDataLatestTime(attentionData.getAttentionTime());
            attentionData.setSubscribeNum(0);
            Intent intent = new Intent(LocalBroadCast.ADD_ATTENTION);
            intent.putExtra("isAttention", listBeen.get(requestType/10).getIsJoin()==1);
            intent.putExtra("attentionData", attentionData);
            String groupId = listBeen.get(requestType/10).getId();
            if(!"attentionList".equals(groupId))
                intent.putExtra("groupId", listBeen.get(requestType/10).getId());
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        }
    }

    private AttentionStatusChangedListener listener;
    public void setAttentionStatusChangedListener(AttentionStatusChangedListener listener){
        this.listener = listener;
    }
    public interface AttentionStatusChangedListener{
        void onAttentionStatusChanged(int position, boolean isAttention);
    }
}
